package net.towee.server.bittorrent.bee;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

public class BEValue {

	private Object value;

	public Object getValue() {
		return value;
	}

	public BEValue(byte[] theValue) {
		this.value = theValue;
	}

	public BEValue(String theValue) {
		try {
			this.value = theValue.getBytes("utf-8");
		} catch (UnsupportedEncodingException e) {
			throw new InvalidBEEncodingException("wrong encoding", e);
		}
		;
	}

	public BEValue(Number theValue) {
		this.value = theValue;
	}

	public BEValue(List<BEValue> theValue) {
		this.value = theValue;
	}

	public BEValue(Map<String, BEValue> theValue) {
		this.value = theValue;
	}

	public byte[] bytesValue() {
		return (byte[]) this.value;
	}

	public String stringValue() {
		try {
			String stringValue = new String(this.bytesValue(), "UTF-8");
			return stringValue;
		} catch (UnsupportedEncodingException e) {
			throw new InvalidBEEncodingException("wrong encoding", e);
		}
	}

	public int integerValue() {
		return ((Number) this.value).intValue();
	}

	public long longValue() {
		return ((Number) this.value).longValue();
	}

	public List<BEValue> listValue() {
		return (List<BEValue>) this.value;
	}

	public Map<String, BEValue> mapValue() {
		return (Map<String, BEValue>) this.value;
	}

	@Override
	public String toString() {
		if (value instanceof byte[]) {
			byte[] bs = (byte[]) value;

			String candidataString = new String(bs);
			if (candidataString.matches("\\p{ASCII}*")) {
				return "\"" + candidataString + "\"";
			} else {
				return "BYTES:" + bs.length;
			}
		} else if (value instanceof Number) {
			return value.toString();
		} else if (value instanceof List) {
			return value.toString();
		} else if (value instanceof Map) {
			return value.toString();
		} else {
			return "ERROR";
		}

	}

}